""" 
项目名称 屈臣氏回馈金签到
入口：#小程序://屈臣氏/p4PXyRIEkAJccuw
cron: 14 8 * * *
new Env("屈臣氏")
比如cloudapi/v2/users/tasks
要去掉authorization的Bearer
变量
  authorization#unionid#openid#备注（没有备注也可以）

变量名 qsccs
多账号   换行/回车
例如
Authorization: Bearer M。。。。。s
export qsccs="M。。。。。s#unionid#openid"
脚本作者: QGh3amllamll  

刚开始学的时候写的   有时候在重新写
---版本说明---
1.0正式版  时间2023年11月29日08:20:28

1.1有时间在重新写   打印每日获得数据
""" 
import os
import requests
import time
import random
from datetime import datetime, timezone, timedelta
import json
import sys

# 控制变量
enable_notification = 1  # 设置为0将不发送通知，设置为1则发送通知

# 只有在需要发送通知时才尝试导入notify模块
if enable_notification == 1:
    try:
        from notify import send
    except ModuleNotFoundError:
        print("警告：未找到notify.py模块。它不是一个依赖项，请勿错误安装。程序将退出。")
        sys.exit(1)




# 配置参数
base_url = "https://mystore-01api.watsonsvip.com.cn"
user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36"

def get_beijing_date():
    beijing_time = datetime.now(timezone(timedelta(hours=8)))
    return beijing_time.date()

def log(message):
    print(message)

def print_disclaimer():
    log("📢 请认真阅读以下声明")
    log("      【免责声明】         ")
    log("✨ 脚本及其中涉及的任何解密分析程序，仅用于测试和学习研究")
    log("✨ 禁止用于商业用途，不能保证其合法性，准确性，完整性和有效性，请根据情况自行判断")
    log("✨ 禁止任何公众号、自媒体进行任何形式的转载、发布")
    log("✨ 本人对任何脚本问题概不负责，包括但不限于由任何脚本错误导致的任何损失或损害")
    log("✨ 脚本文件请在下载试用后24小时内自行删除")
    log("✨ 脚本文件如有不慎被破解或修改由破解或修改者承担")
    log("✨ 如不接受此条款请立即删除脚本文件")
    log("" * 10)
    log(f'-----------心喜查询库存  1.0-----------')
    log(f'这个是怎么东西？？？')
    log(f'U2FsdGVkX1/F371b27nTzUeMknDFjABXyQBHINWvVPRkUVoUe6ZdZ508DVGF7dMc')



def get_env_variable(var_name):
    value = os.getenv(var_name)
    if value is None:
        print(f'环境变量{var_name}未设置，请检查。')
        return None

    accounts_data = [account.split('#') for account in value.strip().split('\n')]
    num_accounts = len(accounts_data)
    print(f'-----------本次账号运行数量：{num_accounts}-----------')
    print_disclaimer()

    return accounts_data


def qcsqd(authorization, union_id, open_id):  # 签到
    urlqd = f"{base_url}/wx/signIn/iter/sign"
    headers = {
        "User-Agent": user_agent,
        "Content-Type": "application/json",
        "Authorization": f"Bearer {authorization}",
        "authorizer-appid": "wx1ffbd6927043dff7",
        "openId": open_id,
        "unionId": union_id,
        "Referer": "https://servicewechat.com/wx1ffbd6927043dff7/543/page-frame.html",
        "miniprogramversion": "1.0.0"
    }
    body = json.dumps({"unionId": union_id, "isSorttion": False})

    try:
        response = requests.post(urlqd, headers=headers, data=body)
        response.raise_for_status()
        response_data = response.json()
        #print(response_data)
        if response_data.get("code") == 0:
            continue_days = response_data['result'].get('continueDays', '未知')
            reward_amount = response_data['result'].get('rewardAmount', '未知')
            print(f"每日回馈金签到: 成功, 连续签到: {continue_days}, 奖励金额: {reward_amount} 🎉")
        elif response_data.get("code") == 11000:
            print(f"每日回馈金签到: {response_data['errorMsg']} 🎉")
        else:
            print(f"每日回馈金签到: 失败 ❌ 了呢, 原因未知！\n {response_data}")
    except requests.exceptions.RequestException as e:
        print(f"请求失败: {e}")



def pdrwwcd(authorization, union_id, open_id):# 判断任务今日是否已经完成
    url = "https://mystore-01api.watsonsvip.com.cn/cloudapi/v2/users/bubbles/filterNot/taskType/4"
    headers = {
        "Authorization": f"Bearer {authorization}",
        "Content-Type": "application/json",
        "authorizer-appid": "wx1ffbd6927043dff7",
        "User-Agent": user_agent, 
        "openId": open_id,
        "unionId": union_id,
    }

    try:
        response = requests.get(url, headers=headers)
        response.raise_for_status()
        rewards_data = response.json()
        #print(rewards_data)
        if not rewards_data['result']:

            print("今日任务已完成或没有任务可做")
            return False  # 今日无任务或任务已完成

        else:
            task_available = False
            for task in rewards_data['result']:
                if 'taskInfo' in task and 'id' in task['taskInfo']:
                    print("任务可用，准备开始做任务")
                    task_available = True
                    break  # 如果找到可用任务，跳出循环

            return task_available  # 返回任务是否可用

    except requests.exceptions.RequestException as e:
        print(f"请求失败: {e}")
        return False  # 请求失败，返回 False
    except Exception as e:
        print(f"发生错误: {e}")
        return False  # 发生其他错误，也返回 False



def hqrwlb(authorization, union_id, open_id):  # 获取任务列表
    #authorization, open_id, union_id = account_info
    base_url2 = "https://mystore-01api.watsonsvip.com.cn/cloudapi/v2/users/tasks"
    headers = {
        "User-Agent": user_agent,
        "Authorization": f"Bearer {authorization}",
        "Content-Type": "application/json",
        "authorizer-appid": "wx1ffbd6927043dff7",
        "openId": open_id,
        "unionId": union_id,
        # 其他需要的头部信息
    }

    try:
        response = requests.get(base_url2, headers=headers)
        response.raise_for_status()
        try:
            response_data = response.json()
            if response_data.get("code") == 0 and "result" in response_data and "list" in response_data["result"]:
                tasks = response_data["result"]["list"]
                browse_tasks = []
                jump_subscribe_tasks = []
                other_tasks = []

                # 分类任务
                for task in tasks:
                    task_id = task.get("id")
                    task_name = task.get("name")
                    task_type = task.get("type")

                    if task_type == "Browse":
                        browse_tasks.append((task_id, task_name))
                    elif task_type in ["Jump", "Subscribe"]:
                        jump_subscribe_tasks.append((task_id, task_name))
                    else:
                        other_tasks.append((task_id, task_name))

                # 打印任务
                if jump_subscribe_tasks:
                    print("-----跳转/订阅类任务-------")#jump
                    for task_id, task_name in jump_subscribe_tasks:
                        print(f"ID: {task_id}, 名称: {task_name}")
                        jumprw(authorization, union_id, open_id, task_id)

                if browse_tasks:
                    print("-----浏览类任务-----") #browse
                    for task_id, task_name in browse_tasks:
                        print(f"ID: {task_id}, 名称: {task_name}")
                        browse(authorization, union_id, open_id, task_id)

                if other_tasks:
                    print("-----其他类型任务-----")#
                    for task_id, task_name in other_tasks:
                        print(f"ID: {task_id}, 名称: {task_name}")
            else:
                print("未能获取有效的任务数据。")
            return response_data
        except ValueError:
            print("响应不是有效的JSON格式。")
            return None
    except requests.exceptions.RequestException as e:
        print(f"请求失败: {e}")
        return None


def jumprw(authorization, union_id, open_id, task_id): #跳转/订阅类任务
    #authorization, open_id, union_id = account_info
    url = "https://mystore-01api.watsonsvip.com.cn/cloudapi/v2/users/tasks/complete"

    headers = {
        "Authorization": f"Bearer {authorization}",
        "Content-Type": "application/json",
        "authorizer-appid": "wx1ffbd6927043dff7",
        "openId": open_id,
        "unionId": union_id,
        # 可能还需要其他头部信息
    }


    data = {
        "taskId": task_id
    }

    try:
        response = requests.post(url, json=data, headers=headers)
        response.raise_for_status()
        # 处理响应
        if response.status_code == 200:
            print(f"任务 {task_id} 完成成功。")
        else:
            print(f"任务 {task_id} 完成失败。")
        
        # 暂停1到3秒
        sleep_time = random.randint(1, 3)
        print(f"暂停 {sleep_time} 秒...")
        time.sleep(sleep_time)

        return response.json()
    except requests.exceptions.RequestException as e:
        print(f"请求失败: {e}")
        return None


"""   代码写错 出现bug 浏览任务   等下要重新写
    def browse(task_id, account_info): # 获取浏览类任务  token  
        url = f"https://mystore-01api.watsonsvip.com.cn/cloudapi/v2/users/tasks/browserTask/token/{task_id}"
        authorization, open_id, union_id = account_info

        headers = {
            "Authorization": f"Bearer {authorization}",
            "Content-Type": "application/json",
            "xweb_xhr": "1",
            "openId": open_id,
            "unionId": union_id,
            "miniProgramVersion": "1.0.0",
            "Accept": "*/*",
            "Sec-Fetch-Site": "cross-site",
            "Sec-Fetch-Mode": "cors",
            "Sec-Fetch-Dest": "empty",
            "Accept-Encoding": "gzip, deflate, br",
            "Accept-Language": "zh-CN,zh;q=0.9"
        }

        try:
            # 获取浏览任务的令牌
            response = requests.get(url, headers=headers)
            response.raise_for_status()
            result = response.json()
            #print(result)
            token = result.get('result', {}).get('token')
            #print(token)
            if token:
                # 暂停10-13秒模拟浏览
                time.sleep(random.randint(10, 13))
                # 提交任务完成
                return tjllrw(task_id, token, account_info, headers)
            else:
                print("未获取到有效的token")
                return None
        except requests.exceptions.RequestException as e:
            print(f"执行浏览任务失败: {e}")
            return None

    def tjllrw(task_id, token, account_info, headers): #提交浏览任务 数据
        url = "https://mystore-01api.watsonsvip.com.cn/cloudapi/v2/users/tasks/complete"
        payload = json.dumps({
            "taskId": str(task_id),
            "completeBrowserTaskToken": token
        })
        #print(payload)
        try:
            # 提交任务完成
            response = requests.post(url, headers=headers, data=payload)
            response.raise_for_status()

            # 解析响应数据
            response_data = response.json()
            if response_data.get('code') == 0:
                # 处理成功的请求
                amount = response_data['result'][0]['amount']
                print(f"任务完成，奖励金额为：{amount}")
            elif response_data.get('code') == 11000:
                # 处理重复的请求
                print(f"错误信息：{response_data['errorMsg']}")
            else:
                # 处理其他错误
                print(f"未知错误，错误代码：{response_data.get('code')}")

            return response_data
        except requests.exceptions.RequestException as e:
            print(f"提交任务完成失败: {e}")
            return None
"""

def browse(authorization, union_id, open_id, task_id):  # 执行浏览任务并提交数据
    browse_url = f"https://mystore-01api.watsonsvip.com.cn/cloudapi/v2/users/tasks/browserTask/token/{task_id}"
    complete_url = "https://mystore-01api.watsonsvip.com.cn/cloudapi/v2/users/tasks/complete"
    #authorization, open_id, union_id = account_info

    headers = {
        "Authorization": f"Bearer {authorization}",
        "Content-Type": "application/json",
        "Content-Type": "application/json",
        "xweb_xhr": "1",
        "openId": open_id,
        "unionId": union_id,
        "miniProgramVersion": "1.0.0",
        "Accept": "*/*",
        "Sec-Fetch-Site": "cross-site",
        "Sec-Fetch-Mode": "cors",
        "Sec-Fetch-Dest": "empty",
        "Accept-Encoding": "gzip, deflate, br",
        "Accept-Language": "zh-CN,zh;q=0.9"
    }


    try:
        # 获取浏览任务的令牌
        browse_response = requests.get(browse_url, headers=headers)
        browse_response.raise_for_status()
        browse_result = browse_response.json()
        token = browse_result.get('result', {}).get('token')

        if not token:
            print("未获取到有效的token")
            return None

        # 暂停10-13秒模拟浏览
        time.sleep(random.randint(11, 13))

        # 提交浏览任务数据
        payload = json.dumps({
            "taskId": str(task_id),
            "completeBrowserTaskToken": token
        })
        complete_response = requests.post(complete_url, headers=headers, data=payload)
        complete_response.raise_for_status()

        # 解析响应数据
        complete_data = complete_response.json()
        if complete_data.get('code') == 0:
            # 处理成功的请求
            amount = complete_data['result'][0]['amount']
            print(f"任务完成，奖励金额为：{amount}")
        elif complete_data.get('code') == 11000:
            # 处理重复的请求
            print(f"错误信息：{complete_data['errorMsg']}")
        else:
            # 处理其他错误
            print(f"未知错误，错误代码：{complete_data.get('code')}")

        return complete_data
    except requests.exceptions.RequestException as e:
        print(f"执行任务失败: {e}")
        return None




def lqjlpd(authorization, union_id, open_id):#领取奖励判断
   # authorization, open_id, union_id = account_info
    url = "https://mystore-01api.watsonsvip.com.cn/cloudapi/v2/users/bubbles/filterNot/taskType/4"

    headers = {
        "Authorization": f"Bearer {authorization}",
        "Content-Type": "application/json",
        "authorizer-appid": "wx1ffbd6927043dff7",
        "User-Agent": user_agent,  # 替换为实际的User-Agent
        "openId": open_id,
        "unionId": union_id,
        # 可能还需要其他头部信息
    }

    try:
        response = requests.get(url, headers=headers)
        response.raise_for_status()
        rewards_data = response.json()

        #print("响应数据: ", rewards_data)  # 打印整个响应数据

        print("\n---------👓领取任务和奖励信息🎶------------")
        
        if not rewards_data.get('result'):  # 新增的判断
            print("当前没有可用的任务或奖励。，1️⃣跑个毛线脚本")
            print("😒" * 8)  # 打印分隔线
            

        else:
            for item in rewards_data['result']:
                task_name = item.get('taskName', 'N/A')
                prize_id = item.get('prizeId', 'N/A')
                task_info = item.get('taskInfo', {})
                task_status = task_info.get('effectState', False)

                if task_status:
                    print(f"执行任务: {task_name}, 奖励ID: {prize_id}")
                    tjlqjl(authorization, union_id, open_id, prize_id, task_name)
                    # 在这里调用执行任务的函数或执行相关操作
                
                else:
                    print(f"任务 '{task_name}' 当前状态无效，跳过执行。")
                print("------")

    except requests.exceptions.RequestException as e:
        print(f"请求失败: {e}")
    except Exception as e:
        print(f"发生错误: {e}")
        return []


def tjlqjl(authorization, union_id, open_id, prize_id, task_name):#  提交领取奖励
    #authorization, open_id, union_id = account_info
    url = "https://mystore-01api.watsonsvip.com.cn/cloudapi/v2/users/receive"
    
    headers = {
        "Authorization": f"Bearer {authorization}",
        "Content-Type": "application/json",
        "authorizer-appid": "wx1ffbd6927043dff7",
        "User-Agent": user_agent,
        "openId": open_id,
        "unionId": union_id,
        # 其他头部信息
    }

    data = {"prizeId": prize_id}

    try:
        response = requests.post(url, headers=headers, json=data)
        response.raise_for_status()

        # 提取响应数据
        result = response.json().get('result', {})
        amount_str = result.get('amount')
        state = result.get('state')
        prize_type = result.get('prizeType')

        # 将金额字符串转换为百分比
        amount_percent = float(amount_str) / 100

        print(f"任务 '{task_name}' 执行成功，奖励信息：金额 {amount_percent}, 状态 {state}, 奖励类型 {prize_type}")
        print(f"领取 '{task_name}' 成功，奖励：金额 {amount_percent}")
        
    except requests.exceptions.RequestException as e:
        print(f"执行任务 '{task_name}' 失败: {e}")




#def ye(authorization, union_id, open_id):  # 查看回馈金
def ye(authorization, union_id, open_id, index, remark): # 查看回馈金
    account_info = f"----账号{index}---- {remark}👗\n"  # 添加账号标识和备注
    notification_message = ""  # 初始化 account_info
    lottery_result = None  # 初始化 lottery_result 变量

    url = f"https://mystore-01api.watsonsvip.com.cn/wx/signIn/index?unionId={union_id}"
    headers = {
        "Authorization": f"Bearer {authorization}",
        "Content-Type": "application/json",
        "charset": "utf-8",
        "miniprogramversion": "1.0.0",
        "unionid": union_id,
        "openid": open_id,
        "User-Agent": user_agent,
        "authorizer-appid": "wx1ffbd6927043dff7",
        "Accept-Encoding": "gzip,compress,br,deflate",
        "Referer": "https://servicewechat.com/wx1ffbd6927043dff7/543/page-frame.html"
    }

    try:
        response = requests.get(url, headers=headers)
        response.raise_for_status()
        response_data = response.json()
        
        amount = response_data.get('result', {}).get('amount', 0) / 100
        notification_message += f"回馈金余额：{amount:.2f}\n"

        has_drawn_lottery = response_data.get('result', {}).get('hasDrawnLotteryToday', '未知')
        notification_message += f"今日是否抽奖：{has_drawn_lottery}\n"

        if has_drawn_lottery == 'no':
            response_data = qd7tcj(authorization, union_id, open_id)
            if response_data is not None:
                if response_data['code'] == 0:
                    prize_info = response_data['result']
                    notification_message += f"恭喜获得奖品：{prize_info['name']}，{prize_info['title']}\n"
                elif response_data['code'] == 11000:
                    notification_message += f"抽奖失败：{response_data['errorMsg']}\n"
                else:
                    notification_message += f"未知响应：{response_data}\n"
        elif has_drawn_lottery == 'yes':
            notification_message += "今日已无抽奖机会"
    except requests.exceptions.RequestException as e:
        notification_message += f"完成签到任务请求失败: {e}\n"


    # 在函数的末尾，将单个账号的通知信息添加到账号信息字符串中
    if notification_message:
        account_info += f"" + notification_message + "\n"

    return account_info  # 返回更新后的账号信息字符串







def qd7tcj(authorization, union_id, open_id): #签到7天抽奖
    url = "https://mystore-01api.watsonsvip.com.cn/signIn/turntable/lotteryDraw"
    headers = {
        "Authorization": f"Bearer {authorization}",
        "charset": "utf-8",
        "miniprogramversion": "1.0.0",
        "unionid": union_id,
        "openid": open_id,
        "User-Agent": user_agent,
        "content-type": "application/json",
        "authorizer-appid": "wx1ffbd6927043dff7",
        "Accept-Encoding": "gzip,compress,br,deflate",
        "Referer": "https://servicewechat.com/wx1ffbd6927043dff7/543/page-frame.html",
    }
    #print(headers)
    try:
        response = requests.get(url, headers=headers)
        response.raise_for_status()

        # 处理响应数据
        response_data = response.json()
        return response_data
    except requests.exceptions.RequestException as e:
        print(f"抽奖请求失败: {e}")
        return None



def main():
    var_name = 'qsccs'  # 环境变量名
    accounts = get_env_variable(var_name)
    if not accounts:
        print("没有账户信息")
        return

    account_count = len(accounts)
    print(f"本次账号运行数量：{account_count}")

    all_accounts_info = ""

    # 处理每个账号的任务
    for index, account_info in enumerate(accounts, start=1):
        # 检查账户信息中的元素数量
        if len(account_info) >= 4:
            authorization, union_id, open_id, remark = account_info
        else:
            authorization, union_id, open_id = account_info
            remark = "无备注"

        print(f"----账号{index}/{account_count}----备注: {remark}")
        qcsqd(authorization, union_id, open_id) # 签到

        # 判断今日任务是否需要完成
        if pdrwwcd(authorization, union_id, open_id):
            response_data = hqrwlb(authorization, union_id, open_id)  # 执行任务

        lqjlpd(authorization, union_id, open_id) #领取奖励
        
   
  
   
    for index, account_info in enumerate(accounts, start=1):
        if len(account_info) >= 4:
            authorization, union_id, open_id, remark = account_info
        else:
            authorization, union_id, open_id = account_info
            remark = "无备注"

        account_info_str = ye(authorization, union_id, open_id, index, remark)
        all_accounts_info += account_info_str + "\n"
        print(account_info_str)

    # 所有账号处理完毕后，获取汇总信息并发送通知
    if all_accounts_info:
        send("屈臣氏通知-jie", "所有账户处理完毕\n" + all_accounts_info)

    print("所有账户处理完毕")

if __name__ == "__main__":
    main()
    